<template>
  <div class="cart">
    <h2>购物车</h2>
    <div v-if="cartItems.length === 0">购物车为空</div>
    <div v-else>
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <span>{{ item.name }} - ¥{{ item.price }} - 数量: {{ item.quantity }}</span>
        <button @click="increment(item.id)">+</button>
        <button @click="decrement(item.id)">-</button>
        <button @click="remove(item.id)">删除</button>
      </div>
      <div class="total">总价: ¥{{ totalPrice }}</div>
    </div>
    
    <div class="add-item">
      <h3>添加商品</h3>
      <input v-model="newItem.name" placeholder="商品名称">
      <input v-model.number="newItem.price" type="number" placeholder="价格">
      <button @click="addItem">添加</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newItem: {
        id: Date.now(),
        name: '',
        price: 0
      }
    }
  },
  computed: {
    cartItems() {
      return this.$store.state.cartItems
    },
    totalPrice() {
      return this.$store.getters.totalPrice
    }
  },
  methods: {
    increment(id) {
      this.$store.dispatch('incrementQuantity', id)
    },
    decrement(id) {
      this.$store.dispatch('decrementQuantity', id)
    },
    remove(id) {
      this.$store.dispatch('removeItem', id)
    },
    addItem() {
      if (this.newItem.name && this.newItem.price > 0) {
        this.$store.dispatch('addItem', {
          id: Date.now(),
          name: this.newItem.name,
          price: this.newItem.price
        })
        this.newItem = {
          id: Date.now(),
          name: '',
          price: 0
        }
      }
    }
  }
}
</script>

<style scoped>
.cart {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
.cart-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #eee;
}
.cart-item span {
  flex-grow: 1;
}
button {
  margin-left: 5px;
  padding: 5px 10px;
}
.total {
  font-weight: bold;
  font-size: 1.2em;
  margin-top: 20px;
  padding-top: 10px;

}
.add-item {
  margin-top: 30px;
  padding: 20px;
  border: 1px solid #eee;
}
.add-item input {
  margin-right: 10px;
  padding: 5px;
}
</style>